import { _decorator, Component, EventTouch, Input, log, Material, screen, Sprite, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Main')
export class Main extends Component {

    @property(Sprite)
    public sp: Sprite = null;

    // 材质对象
    private _materi: Material;


    start() {
        this.node.on(Input.EventType.TOUCH_START, this.touchBegin, this);
        this.node.on(Input.EventType.TOUCH_MOVE, this.touchMove, this);
        this.node.on(Input.EventType.TOUCH_END, this.touchEnd, this);

        // 获取材质对象
        this._materi = this.sp.materials[0];

        // 计算窗口或界面的宽高比，该例子是屏幕的宽高比
        let winSize = screen.windowSize;
        let ratio = winSize.width / winSize.height;
        log(ratio)
        // 设置宽高比，得出正圆型
        this._materi.setProperty("wh_ratio", ratio);
    }

    update(deltaTime: number) {

    }


    public touchBegin(event: EventTouch) {
        log(event.getLocation())
        let center = this.getLightCenter(event.getLocation());
        this._materi.setProperty("light_center", center);
    }

    public touchMove(event: EventTouch) {
        let center = this.getLightCenter(event.getLocation());
        this._materi.setProperty("light_center", center);
    }

    public touchEnd(event: EventTouch) {
        this._materi.setProperty("light_center", new Vec2(2.0, 2.0));
    }

    /** 根据touch坐标计算光源中心点 */
    public getLightCenter(pos: Vec2): Vec2 {
        let winSize = screen.windowSize;
        let x = pos.x / (winSize.width / 2) - 1;
        let y = pos.y / (winSize.height / 2) - 1;
        return new Vec2(x, y);
    }
}


